package com.ruoyi.project.wechatprogram.ordermaster.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.project.wechatprogram.wxuser.domain.WxUser;
import com.ruoyi.project.wechatprogram.wxuser.mapper.WxUserMapper;
import com.ruoyi.project.wechatprogram.moneyoperatelog.domain.WxMoneyOperateLog;
import com.ruoyi.project.wechatprogram.moneyoperatelog.mapper.WxMoneyOperateLogMapper;
import com.ruoyi.project.wechatprogram.orderdescription.domain.WxOrderDescription;
import com.ruoyi.project.wechatprogram.orderdescription.mapper.WxOrderDescriptionMapper;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.project.wechatprogram.ordermaster.mapper.WxOrderMasterMapper;
import com.ruoyi.project.wechatprogram.ordermaster.domain.WxOrderMaster;
import com.ruoyi.project.wechatprogram.ordermaster.service.IWxOrderMasterService;
import com.ruoyi.common.utils.text.Convert;
import org.springframework.transaction.annotation.Transactional;

/**
 * 餐品订单Service业务层处理
 *
 * @author sxchen
 * @date 2020-04-15
 */
@Service
public class WxOrderMasterServiceImpl implements IWxOrderMasterService {

    private static final Logger log = LoggerFactory.getLogger(WxOrderMasterServiceImpl.class);
    private static Integer operate_type_up = 0;
    @Autowired
    private WxOrderMasterMapper wxOrderMasterMapper;

    @Autowired
    private WxOrderDescriptionMapper wxOrderDescriptionMapper;

    @Autowired
    private WxUserMapper wxUserMapper;

    @Autowired
    private WxMoneyOperateLogMapper moneyOperateLogMapper;

    /**
     * 查询餐品订单
     *
     * @param id 餐品订单ID
     * @return 餐品订单
     */
    @Override
    public WxOrderMaster selectWxOrderMasterById(Integer id) {
        return wxOrderMasterMapper.selectWxOrderMasterById(id);
    }

    /**
     * 查询餐品订单是否重复
     */
    @Override
    public WxOrderMaster selectWxOrderMasterOrderIsRepeat(WxOrderMaster wxOrderMaster)
    {
        return wxOrderMasterMapper.selectWxOrderMasterOrderIsRepeat(wxOrderMaster);
    }

    /**
     * 查询餐品订单列表
     *
     * @param wxOrderMaster 餐品订单
     * @return 餐品订单
     */
    @Override
    public List<WxOrderMaster> selectWxOrderMasterList(WxOrderMaster wxOrderMaster) {
        return wxOrderMasterMapper.selectWxOrderMasterList(wxOrderMaster);
    }

    /**
     * 查询餐品订单列表，用于订单展示
     *
     * @param wxOrderMaster 餐品订单
     * @return 餐品订单
     */
    @Override
    public List<WxOrderMaster> selectWxOrderMasterListOrder(WxOrderMaster wxOrderMaster)
    {
        return wxOrderMasterMapper.selectWxOrderMasterListOrder(wxOrderMaster);
    }

    /**
     * 新增餐品订单
     *
     * @param wxOrderMaster 餐品订单
     * @return 结果
     */
    @Override
    @Transactional
    public AjaxResult insertWxOrderMaster(WxOrderMaster wxOrderMaster, String items) {

        try {
            Integer successStatus = wxOrderMasterMapper.insertWxOrderMaster(wxOrderMaster);
            if (successStatus <= 0) {
                log.error("插入失败，数据为：" + wxOrderMaster.toString());
                throw new BusinessException("订单插入异常！");
            }
            // 开始解析购物车内容
            JSONArray jsonArray = JSONArray.fromObject(items);
            WxOrderDescription wxOrderDescription = null;
            List<WxOrderDescription> wxOrderDesList = new ArrayList<>();
            // 循环遍历这个数组
            for (int i = 0; i < jsonArray.size(); i++) {
                wxOrderDescription = new WxOrderDescription();
                // 把里面的对象转化为JSONObject
                JSONObject job = jsonArray.getJSONObject(i);
                // 取数据
                wxOrderDescription.setWxOrderId(wxOrderMaster.getId());
                wxOrderDescription.setMenuId(Integer.parseInt(job.get("menuId").toString()));
                wxOrderDescription.setMenuName(job.get("menuName").toString());
                wxOrderDescription.setMenuPictureUrl(job.get("menuPictureUrl").toString());
                wxOrderDescription.setMenuDescription(job.get("menuDescription").toString());
                wxOrderDescription.setCategoryName(job.get("categoryName").toString());
                wxOrderDesList.add(wxOrderDescription);
            }
            // 开始批量插入订单详情
            Integer insertOrderDescStatus = wxOrderDescriptionMapper.insertBatchWxOrderDes(wxOrderDesList);
            if (insertOrderDescStatus <= 0) {
                log.error("插入失败，数据为：" + wxOrderDesList.toString());
                throw new BusinessException("订单详情插入异常！");
            }

        } catch (Exception e) {
            throw new BusinessException("订单插入异常！");
        }

        return AjaxResult.success();
    }

    /**
     * 修改餐品订单
     *
     * @param wxOrderMaster 餐品订单
     * @return 结果
     */
    @Override
    @Transactional
    public AjaxResult updateWxOrderMaster(WxOrderMaster wxOrderMaster) {
        try {
            wxOrderMaster.setUpdateTime(DateUtils.getNowDate());
            WxOrderMaster wxOrder = wxOrderMasterMapper.selectWxOrderMasterById(wxOrderMaster.getId());
            // 订单为空
            if (wxOrder == null) {
                log.error("获取订单为空！");
                return AjaxResult.error("获取订单为空！");
            }
            // 更改订单的状态值
            Integer orderStatus = wxOrderMasterMapper.updateWxOrderMaster(wxOrderMaster);
            if (orderStatus <= 0) {
                log.error("修改订单状态值失败！");
                return AjaxResult.error("获取订单为空！");
            }
            // 查询用户信息
            WxUser wxUser = wxUserMapper.selectWxUserByIphone(wxOrder.getBuyerPhone());
            //保存修改前的金额
            Integer oldBalance = wxUser.getBalance();
            // 更新用户金额
            wxUser.setBalance(wxUser.getBalance() + wxOrder.getOrderPrice());
            Integer userStatus = wxUserMapper.updateWxUserBalanceByPhone(wxUser);
            if (userStatus <= 0) {
                log.error("修改用户金额失败！");
                return AjaxResult.error("获取订单为空！");
            }

            //添加金额变动记录
            WxMoneyOperateLog moneyOperateLog = new WxMoneyOperateLog();
            moneyOperateLog.setUserId(wxUser.getId());
            moneyOperateLog.setIphone(wxUser.getIphone());
            moneyOperateLog.setName(wxUser.getName());
            moneyOperateLog.setType(operate_type_up);
            moneyOperateLog.setBalanceChange(wxOrder.getOrderPrice());
            moneyOperateLog.setBalance(oldBalance + wxOrder.getOrderPrice());
            moneyOperateLog.setCreateTime(new Date());
            moneyOperateLog.setDescription("订单取消");
            moneyOperateLogMapper.insertWxMoneyOperateLog(moneyOperateLog);

            return AjaxResult.success(wxUser);
        } catch (Exception e) {
            log.error("取消订单失败！", e.getMessage());
            throw new BusinessException("取消订单失败！");
        }
    }

    /**
     * 修改餐品订单的就餐状态
     *
     * @param wxOrderMaster 餐品订单
     * @return 结果
     */
    @Override
    public AjaxResult updateOrderStatusByDay(WxOrderMaster wxOrderMaster) {
        Integer result = wxOrderMasterMapper.updateWxOrderMaster(wxOrderMaster);
        if (result > 0){
            return AjaxResult.success();
        }
        return AjaxResult.error();
    }

    /**
     * 删除餐品订单对象
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteWxOrderMasterByIds(String ids) {
        return wxOrderMasterMapper.deleteWxOrderMasterByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除餐品订单信息
     *
     * @param id 餐品订单ID
     * @return 结果
     */
    @Override
    public int deleteWxOrderMasterById(Integer id) {
        return wxOrderMasterMapper.deleteWxOrderMasterById(id);
    }

    /**
     * 报表订单详情按天展示，用于订单展示
     *
     * @param wxOrderMaster 餐品订单
     * @return 餐品订单
     */
    @Override
    public List<WxOrderMaster> selectWxOrderMasterByDay(WxOrderMaster wxOrderMaster)
    {
        return wxOrderMasterMapper.selectWxOrderMasterByDay(wxOrderMaster);
    }
}
